package repository

import (
	"context"
	"strconv"

	"gitee.com/zhyclouds/fable-scribe/internal/domain"
	"gitee.com/zhyclouds/fable-scribe/internal/repository/dao"
)

var (
	ErrMongoRecodeNotFound = dao.ErrMongoRecodeNotFound
)

type ComicRepository interface {
	Insert(ctx context.Context, comic domain.Comic) error
	GetByUid(ctx context.Context, uid int64, offset int, limit int) ([]domain.Comic, error)
	DeleteComicById(ctx context.Context, comicId int64, uid int64) error
}

type MongoDBComicRepository struct {
	dao dao.ComicDAO
}

func NewMongoDBComicRepository(dao dao.ComicDAO) ComicRepository {
	return &MongoDBComicRepository{
		dao: dao,
	}
}

func (repo *MongoDBComicRepository) DeleteComicById(ctx context.Context, comicId int64, uid int64) error {
	return repo.dao.DeleteById(ctx, comicId, uid)
}

func (repo *MongoDBComicRepository) Insert(ctx context.Context, comic domain.Comic) error {
	_, err := repo.dao.Insert(ctx, repo.toEntity(comic))
	return err
}

func (repo *MongoDBComicRepository) GetByUid(ctx context.Context, uid int64, offset int, limit int) ([]domain.Comic, error) {
	comics, err := repo.dao.GetByUid(ctx, uid, offset, limit)
	if err != nil {
		return nil, err
	}

	res := make([]domain.Comic, 0, len(comics))
	for _, comic := range comics {
		res = append(res, repo.toDomain(comic))
	}

	return res, nil
}

func (repo *MongoDBComicRepository) toEntity(comic domain.Comic) dao.Comic {
	// 创建 dao.Comic 对象并复制字段值
	daoComic := dao.Comic{
		Uid:        comic.Uid,
		Text:       comic.Text,
		Style:      comic.Style,
		Tone:       comic.Tone,
		Gender:     comic.Gender,
		Appearance: comic.Appearance,
		Ctime:      comic.Ctime,
		Utime:      comic.Utime,
	}

	// 处理 Draws 数组
	if len(comic.Draws) > 0 {
		daoComic.Draws = make([]dao.Draw, len(comic.Draws))
		for i, draw := range comic.Draws {
			daoComic.Draws[i] = dao.Draw{
				Desc: draw.Desc,
				Url:  draw.Url,
			}
		}
	}

	return daoComic
}

func (repo *MongoDBComicRepository) toDomain(comic dao.Comic) domain.Comic {
	// 创建 domain.Comic 对象并复制字段值
	domainComic := domain.Comic{
		Id:         strconv.FormatInt(comic.Id, 10),
		Uid:        comic.Uid,
		Text:       comic.Text,
		Style:      comic.Style,
		Tone:       comic.Tone,
		Gender:     comic.Gender,
		Appearance: comic.Appearance,
		Ctime:      comic.Ctime,
		Utime:      comic.Utime,
	}

	// 处理 Draws 数组
	if len(comic.Draws) > 0 {
		domainComic.Draws = make([]domain.Draw, len(comic.Draws))
		for i, draw := range comic.Draws {
			domainComic.Draws[i] = domain.Draw{
				Desc: draw.Desc,
				Url:  draw.Url,
			}
		}
	}

	return domainComic
}
